package service

import (
	"fmt"
	"net/http"
	"io/ioutil"
	"encoding/json"
	"strconv"
)

type GameOrder struct {
	PaySign   string `json:"pay_sign"`
	SignType  string `json:"sign_type"`
	Package   string `json:"package"`
	NonceStr  string `json:"nonce_str"`
	Timestamp string `json:"timestamp"`
}

func CreateGameOrder(orderSn, openId string, price float64) (gameOrder *GameOrder, err error) {
	url := fmt.Sprintf("https://mp.leyougame.cc/pay_game?open_id=%s&total_fee=%s&order_sn=%s", openId, strconv.FormatFloat(price, 'f', -1, 64), orderSn)
	fmt.Printf("url: %s\n", url)
	res, err := http.Get(url)
	if err != nil {
		err = fmt.Errorf("[CreateGameOrder]err: %+v\n", err)
		return
	}
	defer res.Body.Close()
	if res.StatusCode != http.StatusOK {
		err = fmt.Errorf("[CreateGameOrder]http.Status: %s", res.Status)
		return
	}

	b, err := ioutil.ReadAll(res.Body)
	if err != nil {
		return
	}

	gameOrder = new(GameOrder)
	if err = json.Unmarshal(b, gameOrder); err != nil {
		err = fmt.Errorf("[CreateGameOrder]parse json failed: %s, err :%+v\n", string(b), err)
		return
	}
	return
}
